package com.wf.smartcomm.server.serviceImpl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wf.smartcomm.server.bean.Version;
import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.model.Page;
import com.wf.smartcomm.server.service.VersionService;
import com.wf.smartcomm.server.util.IdUtils;

@Service
@Transactional
public class VersionServiceImpl implements VersionService {

	@Resource
	private SessionFactory factory;
	
	@Override
	public void save(Version version) {
		version.setObjectId(IdUtils.uuid());
		version.setCreatedAt(String.valueOf(System.currentTimeMillis()));
		factory.getCurrentSession().persist(version);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Version get(String objectId) {
		return (Version) factory.getCurrentSession().get(Version.class, objectId);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public void list(Village village, Page page) {
		Query query = factory.getCurrentSession().createQuery("select count(*) from Version where village =:village");
		query.setParameter("village", village);
		Long counts = (Long) query.uniqueResult();
		page.setTotalCount(counts.intValue());
		query = factory.getCurrentSession().createQuery("from Version where village =:village order by createdAt desc");
		query.setParameter("village", village);
		page.setDataList(query.list());
	}

	@Override
	public Version getLatestVersion(String type) throws Exception {
		Query query = factory.getCurrentSession().createQuery("from Version where type = :type order by createdAt desc").setFirstResult(0).setMaxResults(1);
		query.setParameter("type", type);
		List<Version> versions = query.list();
		if (versions != null && versions.size() > 0) {
			return versions.get(0);
		}
		return null;
	}

}
